package servlet.books;

import com.alibaba.fastjson.JSONObject;
import utils.JdbcUtil;
import utils.ResultData;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 图书信息修改
 */
@WebServlet(urlPatterns = "/booksUpdate")
public class BooksUpdate extends HttpServlet {

    JdbcUtil jdbcUtil = new JdbcUtil();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取参数
        Integer id = Integer.valueOf(req.getParameter("id"));
        String no = req.getParameter("no");
        String name = req.getParameter("name");
        String type = req.getParameter("type");
        String author = req.getParameter("author");
        Integer price = Integer.valueOf(req.getParameter("price"));
        String language = req.getParameter("language");
        //打开jdbc连接
        Connection connection = jdbcUtil.getConnection();
        //更新语句
        String sql = "update book_manage set no=?,name=?,type=?,author=?,price=?,language=? where id=? ";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //设置参数
            preparedStatement.setString(1, no);
            preparedStatement.setString(2, name);
            preparedStatement.setString(3, type);
            preparedStatement.setString(4, author);
            preparedStatement.setInt(5, price);
            preparedStatement.setString(6, language);
            preparedStatement.setInt(7, id);
            //执行更新语句
            int i = preparedStatement.executeUpdate();
            ResultData resultData;
            //判断是否成功
            if (i > 0) {
                resultData = ResultData.success();
            } else {
                resultData = ResultData.fail();
            }
            Object o = JSONObject.toJSON(resultData);
            //返回给前端页面
            resp.getWriter().print(o.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

